package com.dragon.queue;

/**
 * @author dragon
 * @version 1.0
 * @description 循环队列
 * @date created in 2018-12-13
 */
public class LoopQueue<E> implements Queue<E> {

    private E[] elementData;

    private int head;

    private int tail;

    private int size;

    public LoopQueue() {
        this(10);
    }

    public LoopQueue(int capacity) {
        elementData = (E[]) new Object[capacity + 1];
        head = 0;
        tail = 0;
        size = 0;
    }

    /**
     * 出队
     *
     * @return
     */
    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Cannot dequeue from an empty queue");
        }
        E ret = elementData[head];
        elementData[head] = null;
        head = (head + 1) % elementData.length;
        size--;
        if (size == getCapacity() / 4 && getCapacity() / 2 != 0) {
            resize(getCapacity() / 2);
        }
        return ret;
    }

    /**
     * 入队
     *
     * @param e
     */
    @Override
    public void enqueue(E e) {
        //循环数组
        if ((tail + 1) % elementData.length == head) {
            resize(getCapacity() + getCapacity() / 2);
        }
        elementData[tail] = e;
        tail = (tail + 1) % elementData.length;
        size++;
    }

    /**
     * 得到容量
     *
     * @return
     */
    private int getCapacity() {
        return elementData.length - 1;
    }

    /**
     * 扩容
     *
     * @param capacity
     */
    public void resize(int capacity) {
        E[] newArray = (E[]) new Object[capacity + 1];
        for (int i = 0; i < newArray.length; i++) {
            newArray[i] = elementData[(i + head) % elementData.length];
        }
        elementData = newArray;
        head = 0;
        tail = size;
    }

    /**
     * 返回循环队列的长度
     *
     * @return
     */
    @Override
    public int size() {
        return size;
    }

    /**
     * 判断循环队列元素是否为空
     *
     * @return
     */
    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    /**
     * 得到循环队列的头
     *
     * @return
     */
    @Override
    public E getHead() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Queue is empty.");
        }
        return elementData[head];
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        res.append(String.format("Queue: size = %d , capacity = %d\n", size, getCapacity()));
        res.append("head [");
        for (int i = head; i != tail; i = (i + 1) % elementData.length) {
            res.append(elementData[i]);
            if ((i + 1) % elementData.length != tail) {
                res.append(", ");
            }
        }
        res.append("] tail");
        return res.toString();
    }
}
